/**
 * @copyright Copyright (c) 2025 CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author Xie Jinhui
 */

/* 
 * Include standard input/output library for file operations and printf functions
 * Provides FILE type, printf, fopen, fclose and other standard I/O operations
 * Essential for any C program that needs console or file output capabilities
 */
#include <stdio.h>

/* 
 * Include standard library for memory allocation and process control
 * Provides malloc, free, exit, system and other general purpose functions
 * Required for dynamic memory management and program termination
 */
#include <stdlib.h>

/* 
 * Include string manipulation library for string operations
 * Provides strlen, strcpy, strcat, strcmp and other string handling functions
 * Necessary for working with character arrays and string processing
 */
#include <string.h>

/* 
 * Include system logging facility for centralized log management
 * Provides syslog interface for sending messages to system logger daemon
 * Enables standardized logging across the operating system
 */
#include <syslog.h>

/* 
 * Include custom log management header file for function declarations
 * Contains prototypes for init_log, write_log, and close_log functions
 * Ensures consistency between function declarations and implementations
 */
#include "log_manage.h"

/* 
 * Include variable argument handling for functions with variable parameters
 * Provides va_list, va_start, va_arg, va_end for variable argument processing
 * Required for implementing printf-style functions with flexible arguments
 */
#include <stdarg.h>

/* 
 * Initialize the system logging facility with application-specific settings
 * This function sets up the connection to the system logger daemon
 * Configures logging options including process ID and fallback to console
 * Must be called before any write_log operations to ensure proper logging
 */
void init_log() {
    /* 
     * Open connection to system logger with specified parameters
     * First parameter "appctl" identifies the application in log entries
     * LOG_PID option includes process ID in each log message for tracking
     * LOG_CONS option falls back to console if syslog is unavailable
     * LOG_USER facility specifies general user-level message classification
     */
    openlog("appctl", LOG_PID | LOG_CONS, LOG_USER);
}

/* 
 * Write formatted log messages to the system logging facility
 * This function provides a unified interface for logging at various severity levels
 * Supports variable arguments like printf for flexible message formatting
 * Routes messages to appropriate syslog priority levels based on severity
 */
void write_log(int level, const char *fmt, ...) {
    /* 
     * Declare variable argument list for handling flexible parameters
     * va_list type is used to traverse the variable arguments passed to function
     * This enables printf-style formatting with dynamic number of arguments
     */
    va_list ap;
    
    /* 
     * Initialize variable argument list for processing
     * va_start macro initializes the va_list to point to first variable argument
     * fmt parameter is the last fixed parameter before variable arguments begin
     * This setup allows access to all additional arguments passed to the function
     */
    va_start(ap, fmt);
    
    /* 
     * Route log messages to appropriate syslog priority based on severity level
     * This switch statement maps application log levels to system log priorities
     * Ensures consistent log level translation across the application
     */
    switch (level) {
        /* 
         * Handle debug level messages for detailed development information
         * DEBUG level is for verbose information useful during development
         * These messages are typically disabled in production environments
         * Mapped to LOG_DEBUG system priority for low-importance messages
         */
        case MSG_DEBUG:
            /* 
             * Send formatted debug message to system logger
             * vsyslog function accepts variable arguments like vprintf
             * LOG_DEBUG priority indicates informational messages for debugging
             * These messages help developers trace program execution flow
             */
            vsyslog(LOG_DEBUG, fmt, ap);
            break;
            
        /* 
         * Handle informational level messages for normal operational events
         * INFO level is for general information about application operation
         * These messages confirm that the application is functioning normally
         * Mapped to LOG_INFO system priority for routine notifications
         */
        case MSG_INFO:
            /* 
             * Send formatted informational message to system logger
             * LOG_INFO priority indicates normal operational messages
             * Used for tracking significant application milestones and states
             * Typically enabled in production for monitoring application health
             */
            vsyslog(LOG_INFO, fmt, ap);
            break;
            
        /* 
         * Handle warning level messages for potentially problematic conditions
         * WARNING level indicates situations that might require attention
         * These messages highlight unusual but non-critical conditions
         * Mapped to LOG_WARNING system priority for alert messages
         */
        case MSG_WARNING:
            /* 
             * Send formatted warning message to system logger
             * LOG_WARNING priority indicates conditions that are not errors
             * but may indicate potential future problems or unusual situations
             * Used for events that don't prevent operation but merit monitoring
             */
            vsyslog(LOG_WARNING, fmt, ap);
            break;
            
        /* 
         * Handle error level messages for critical operational failures
         * ERROR level indicates serious problems that prevent normal operation
         * These messages highlight conditions that require immediate attention
         * Mapped to LOG_ERR system priority for error conditions
         */
        case MSG_ERROR:
            /* 
             * Send formatted error message to system logger
             * LOG_ERR priority indicates error conditions that need intervention
             * Used for reporting failures in application functionality
             * These messages are always logged regardless of configuration
             */
            vsyslog(LOG_ERR, fmt, ap);
            break;
            
        /* 
         * Handle unknown log levels with a safe default behavior
         * This default case ensures the function doesn't crash on invalid levels
         * Provides graceful degradation when unexpected level values are passed
         * Uses INFO level as safe default for unknown severity classifications
         */
        default:
            /* 
             * Send formatted message with default INFO priority
             * This ensures that even with invalid level parameters, message is logged
             * LOG_INFO provides neutral priority that won't trigger unnecessary alerts
             * Maintains logging functionality while handling edge cases gracefully
             */
            vsyslog(LOG_INFO, fmt, ap);
            break;
    }
    
    /* 
     * Clean up variable argument list after processing is complete
     * va_end macro performs necessary cleanup of the va_list structure
     * This is required to ensure proper stack management and avoid memory issues
     * Must be called after processing all variable arguments
     */
    va_end(ap);
}

/* 
 * Close the connection to the system logging facility
 * This function properly terminates the logging subsystem connection
 * Ensures all buffered log messages are flushed to the system logger
 * Should be called during application shutdown for clean termination
 */
void close_log() {
    /* 
     * Close the connection to system logger and release associated resources
     * closelog function terminates the connection opened by openlog
     * Ensures any buffered log messages are written before connection close
     * Proper cleanup prevents resource leaks and ensures complete log delivery
     */
    closelog();
}